package org.glorylight.hacks.social.service;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.glorylight.hacks.social.data.TipsData;
import org.glorylight.hacks.social.model.Tips;
import org.glorylight.hacks.social.model.TipsDetail;
import org.glorylight.hacks.social.util.ModelHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly=true)
public class TipsService extends BaseService{
	private static final Logger log = LoggerFactory.getLogger(TipsService.class);
	
	@Transactional(readOnly = false)
	public void addTips(TipsData tipsData) throws Exception {
		if (log.isDebugEnabled())
			log.debug("creating new tipsData and tipsDetail : {}",tipsData.getId());
		Tips tips = generateTips(tipsData);
		add(tips);
	}
	
	@Transactional(readOnly = false)
	public void deleteTips(TipsData tipsData) throws Exception {
		if (log.isDebugEnabled())
			log.debug("deleting tipsData and tipsDetail : {}",tipsData.getId());
		Tips tips = generateTips(tipsData);
		delete(tips);
	}
	
	@Transactional(readOnly = false)
	public void updateTips(TipsData tipsData) throws Exception {
		if (log.isDebugEnabled())
			log.debug("deleting tipsData and tipsDetail : {}",tipsData.getId());
		Tips tips = generateTips(tipsData);
		update(tips);
	}
	
	private Tips generateTips(TipsData tipsData) {
		TipsDetail detail = new TipsDetail(tipsData.getId(), ArrayUtils.toObject(tipsData.getTipsDetail().getBytes()));
		Tips tips = new Tips(tipsData.getId(), tipsData.getStartAge(), tipsData.getEndAge(), 
				tipsData.getTags(), tipsData.getTitle(), detail);
		detail.setTips(tips);
		return tips;
	}
	
	public List<TipsData> findTipsData(float age) {
		if (log.isDebugEnabled())
			log.debug("getting tips data by age : {}", age);
		List<Tips> tipsRecords = em.createNamedQuery("tips-by-age", Tips.class)
				.setParameter("age", age).getResultList();
		List<TipsData> tipsDatas = null;
		if (!tipsRecords.isEmpty()) {
			tipsDatas = new ArrayList<TipsData>();
			for (Tips tips : tipsRecords) {
				TipsDetail tipsDetail = em.find(TipsDetail.class, tips.getId());
				tipsDatas.add(ModelHelper.convertTips(tips, tipsDetail));
			}
		}
		return tipsDatas;
	}
}
